package com.bwie.gateway.filter;


import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AuthFilter implements Ordered, GlobalFilter {
    @Autowired
    private IgnoreWhiteConfig ignoreWhiteConfig;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        List<String> whites = ignoreWhiteConfig.getWhites();
        if (StringUtils.matches(path,whites)){
           return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        // token 非空验证
        if (StringUtils.isEmpty(token)) {
            // 不放行 提示错误信息
            return GatewayUtils.errorResponse(exchange, "token不能为空！");
        }
        try {
            // token 合法性性
            JwtUtils.parseToken(token);
        } catch (Exception ex) {
            return GatewayUtils.errorResponse(exchange, "token格式错误！");
        }
        // token 是否过期
        // 获取 UserKey
        String userKey = JwtUtils.getUserKey(token);
        if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)) {
            return GatewayUtils.errorResponse(exchange, "token过期！");
        }
        //续期
        // 从redis 取
        String userJson = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        if (redisTemplate.getExpire(TokenConstants.LOGIN_TOKEN_KEY + userKey)<5){
            redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY + userKey,15,TimeUnit.MINUTES);
        }
        // 放行
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
